package com.neuedu.boot.controller;


import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
public class UploadAndDownloadController {

    public static final String  UPLOAD_DIR  ="D:\\upload";


    @RequestMapping("/upload")
//    @ResponseBody
    String upload(MultipartFile pic) throws IOException {

        //将临时目录中的 pic,转储到 硬盘中、FastDFS
        String oriName = pic.getOriginalFilename(); //aaaa.jpg  bbb.png
        String ext = oriName.substring(oriName.lastIndexOf("."));
        File dest = new File(UPLOAD_DIR, UUID.randomUUID().toString()+ext);

        pic.transferTo(dest);

        //需要存储到数据库中,省略了
        //上传成功之后 查询列表
        return "redirect:/listfile";
    }


    /**
     * 模拟从数据库查询数据
     */
    @RequestMapping("/listfile")
    String listfile(ModelMap model) throws IOException {


        //模拟从数据库查询出上传的文件
        File dir = new File(UPLOAD_DIR);
        File[] files = dir.listFiles();
        model.addAttribute("files",files);

        return "file_list.jsp";
    }


    @RequestMapping("/download")
    ResponseEntity download(String filename){
        //即将要下载的目标文件
        File dest = new File(UPLOAD_DIR,filename);

        //1通过Response的IO操作 输出到客户端


        //2使用ResponseEntity 将内容输出给客户端
        //attachment 告诉浏览器，内容不要直接打开，显示下载框
        return ResponseEntity.ok().header(HttpHeaders.CONTENT_TYPE,"application/octet-stream").
                header(HttpHeaders.CONTENT_DISPOSITION,"attachment;filename="+filename).
                body(new FileSystemResource(dest));

    }







}
